<template>
  <div id="dialogPubWork">
    <el-dialog
      class="about-set"
      title="发布作品小视频"
      :visible.sync="dialogData.isShow"
      width="600px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="选择活动" prop="activityId">
            <el-select
              v-model="ruleForm.activityId"
              filterable
              placeholder="选择活动"
            >
              <el-option
                v-for="item in activityList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <showTagSelect
            channel="SHORT_VIDEO"
            @getTagIds="getTagIds"
          ></showTagSelect>
          <el-form-item label="作品类型" prop="type">
            <el-radio-group v-model="ruleForm.type">
              <el-radio
                v-for="item in typeList"
                :key="item.dictValue"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择学院" prop="collegeId">
            <el-select
              v-model="ruleForm.collegeId"
              filterable
              placeholder="选择学院"
            >
              <el-option
                v-for="item in collegeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择马甲" prop="robot">
            <el-select
              v-model="ruleForm.robot"
              filterable
              placeholder="请选择马甲"
              :disabled="ruleForm.canRobotRandom === true"
            >
              <el-option
                v-for="item in vestList"
                :key="item.robotId"
                :label="item.robotName"
                :value="item.robotId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="随机马甲">
            <el-switch
              v-model="ruleForm.canRobotRandom"
              :active-value="true"
              :inactive-value="false"
              active-color="#1DC8A4"
              @change="changeRandom(ruleForm.canRobotRandom)"
            ></el-switch>
          </el-form-item>
          <el-form-item label="作品内容" prop="content">
            <el-input
              v-model="ruleForm.content"
              type="textarea"
              maxlength="200"
              show-word-limit
            ></el-input>
          </el-form-item>
          <!--作品类型为小视频-->
          <el-form-item
            v-show="ruleForm.type === 'VIDEO'"
            label="添加作品"
            prop="videoId"
          >
            <el-button id="upload" type="warning">
              上传视频
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import showTagSelect from '@common/showTagSelect' // 显性标签下拉选择公共组件
import { pubWork } from '@/api/videoManagement/work' // 接口
import { getVideoPara } from '@utils/pubFunction'
import { uploadVideo } from '@utils/uploadVideo'
import {
  sysNormalDisable,
  getVestList,
  getWorkListActivities,
  getRandomRobotId
} from '@utils/dictionariesFunc'
export default {
  name: 'DialogPubWork',
  msg: '小视频管理-作品管理-我的发布---发布作品',
  components: {
    showTagSelect
  },
  props: ['dialogData'],
  data() {
    return {
      loading: false,
      collegeList: [], // 学院
      vestList: [{ robotId: '', robotName: '- 请选择马甲 -' }], // 选择马甲
      typeList: [{ dictLabel: '小视频', dictValue: 'VIDEO' }], // 作品类型
      activityList: [{ id: '', name: '- 请选择关联活动 -' }], // 活动列表
      ruleForm: {
        collegeId: '', // 学院
        userId: '', // 用户id
        robot: '', // 马甲
        canRobotRandom: true, //是否为随机马甲，为true的话系统后端默认随机一个马甲
        type: 'VIDEO', // 作品类型
        content: '', // 作品内容
        videoId: '', // 视频vid
        whOperator: ''
      },
      rules: {
        collegeId: { required: true, message: 'content' },
        // robot: { required: true, message: '请选择马甲' },
        robot: {},
        type: { required: true, message: '请选择作品类型' },
        content: {
          required: true,
          message: '作品内容不能为空',
          trigger: 'change'
        },
        videoId: { required: true, message: '请上传视频' }
      },
      polivNum: {
        polyvUserId: '',
        polyvSecretKey: '',
        polyvWriteToken: '',
        polyvReadToken: ''
      },
      upVideo: null,
      labelItems: []
    }
  },
  computed: {
    dapengUserId() {
      return this.$store.state.user.dapengUserId
    }
  },
  watch: {
    'ruleForm.canRobotRandom': {
      // 监听随机马甲
      handler(newValue, oldValue) {
        if (newValue === true) {
          // 随机马甲启用
          this.rules.robot = {}
        } else {
          // 随机马甲关闭
          this.rules.robot = { required: true, message: '请选择马甲' }
        }
      },
      deep: true
    }
  },
  mounted() {
    this.getStatusList()
    this.getPolivNum()
  },
  methods: {
    /* 获取系统配置-保利威视 */
    getPolivNum() {
      let _this = this
      getVideoPara().then((data) => {
        this.polivNum = { ...data }
        uploadVideo(_this.polivNum, _this.saveVideo).then((resObj) => {
          _this.upVideo = resObj
        })
      })
    },
    /* 获取数据状态 */
    async getStatusList() {
      // 学院
      this.collegeList = await sysNormalDisable('sys_college')
      this.ruleForm.collegeId = this.collegeList[0].dictValue
      // 马甲
      let data1 = await getVestList(this.dapengUserId)
      this.vestList = this.vestList.concat(data1)
      // 活动列表
      let data = await getWorkListActivities('WORKS', { stauts: 'ONGOING' })
      this.activityList = this.activityList.concat(data)
    },
    /* 保存上传视频 */
    saveVideo(fileData) {
      this.ruleForm.videoId = fileData.vid
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.upVideo.update({
        uploadSuccess: ''
      })
      clearInterval(this.upVideo.timer)
      this.upVideo.destroy()
      this.dialogData.isShow = false
    },
    /* 改变随机马甲按钮状态 */
    changeRandom(status) {
      if (status === 'on') {
        // 启用随机马甲
        if (this.vestList.length === 0) {
          this.$message({
            message: '马甲列表为空，无法选择随机马甲',
            type: 'error'
          })
          this.ruleForm.canRobotRandom = true
        }
      }
    },
    /*整合选择的标签*/
    setIabelInfos() {
      let ary = []
      this.labelItems.forEach((item, index) => {
        let { labelProperty: labelCategoryProperty, labelId, labelName } = item
        let obj = {
          labelCategoryProperty,
          labelId,
          labelName
        }
        ary.push(obj)
      })
      return [...ary]
    },
    /* 确认提交 */
    async confirmLabel(formName) {
      this.loading = true
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let obj = { ...this.ruleForm }
          delete obj.robot
          // userId,随机马甲时，取随机马甲，否则取当前马甲的robotId
          if (this.ruleForm.canRobotRandom === true) {
            obj.userId = (await getRandomRobotId(this.dapengUserId)) || ''
          } else {
            obj.userId = this.ruleForm.robot
          }
          obj.whOperator = this.dapengUserId
          //选中标签
          obj.labelInfos = this.setIabelInfos()
          pubWork(
            obj,
            (response) => {
              this.loading = false
              this.$emit('refresh')
              this.cancelLabel()
            },
            (response) => {
              this.loading = false
              this.$message.warning('发布作品失败，' + response.message)
            }
          )
        } else {
          this.loading = false
          return false
        }
      })
    },
    /* 获取选中的显性标签 */
    getTagIds(items) {
      this.labelItems = [...items]
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less">
#dialogPubWork {
  @import url('~@common/style/textarea.less');
}
</style>
